import store from '../store/index'
import ajax from '@/components/ajax.js'
import axios from "axios"
import { getSid,getToken } from '@/utils/auth'
import urlparam from "@/api/ps_form.js"
function _getRealUrl(url,istoken,config){
  config=config||{}
  url=urlparam.realUrl(url,config.urlparam)
  if(istoken){
    let token=getToken();
    if(_.isEmpty(token)){
      store.dispatch("user/resetToken")
      store.dispatch('tagsView/delAllViews', null, { root: true })
     // router.push("/login")
      return ;
    }
    let sid=getSid();
    if(url&&url.indexOf("token")==-1){
      url+=(url.indexOf("?")==-1?"?":"&")+"token="+token+"&_SID="+sid;
    }
  }
  if(url.indexOf("_VIEWER")==-1)
  url+=(url.indexOf("?")==-1?"?":"&")+"_VIEWER=APP"
  if(url.indexOf("_PID")==-1){
    url+=(url.indexOf("?")==-1?"?":"&")+"_PID="+getRandom()
  }
  return url;
}
function getRandom(){
  return new Date().getTime()+((1+Math.random())*1000).toFixed("2")+"";
}
export const getRealUrl=_getRealUrl;
export function syncRequest(config){

    config.url=_getRealUrl(config.url,true,config);
    config.async=false;
    config.dataType='json'
    config.type=config.method?config.method:"get"
    let responseJSON={};
    let $store=store;
    config.success=function(data){
      responseJSON =data;
    }
    config.error=function(state,stateText){
      responseJSON ={error:true,state:state,stateText:stateText};
    }
    ajax(config);

    if(responseJSON.result=='LOGON' && responseJSON.errorCode=='-5'){
      setTimeout(function(){
        $store.dispatch("user/resetToken")
        $store.dispatch('tagsView/delAllViews', null, { root: true })
      },20)
     // router.push("/login")
      return ;
    }
    let token=responseJSON.token,sid=responseJSON._SID;
    if(store && token && sid)
    store.dispatch("user/setUserToken",{token:token,_SID:sid})
   // let {responseJSON}=ajax(config)
   return responseJSON
}
export function fileUpload(url,formData,urlparam,onUploadProgress=(e)=>{}){
  url=_getRealUrl(url,true,{urlparam:urlparam});
  if(url){
    return axios({
      url:url,
      method:'post',
      data:formData,
      onUploadProgress:onUploadProgress,
      headers:{'Content-Type':'multipart/form-data'}
    })
  }else{
    return new Promise((resolve,reject)=>{
      resolve({message:'url错误'})
    })
  }
}
const urlEncode = function(param, key, encode) {
  if (param==null) return '';
  var paramStr = '';
  var t = typeof (param);
  if (t == 'string' || t == 'number' || t == 'boolean') {
      paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param);
  } else {
      for (var i in param) {
          var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
          paramStr += urlEncode(param[i], k, encode)
      }
  }
  return paramStr;

}
export function fileDownload(url, config = {}) {
  if(!url)return;
  url=_getRealUrl(url,true,{urlparam:config.urlparam});
  let form = document.getElementById("__downloadform__")
  if(!form){
    form=document.createElement("form");
    form.style.display='none';
    form.id='__downloadform__'
    document.body.appendChild(form);
  }
  form.innerHTML="";
  let s=[];
  if(config.voParam){
    let objs=["number","string","undefined","boolean","object"];
      let voParam=config.voParam;
      let _param={};
      for(let s in voParam){
        if(objs.indexOf(typeof s) && !_.isEmpty(voParam[s])){
          _param['vo.string('+s+")"]=voParam[s];
        }
      }
      config.param=config.param||{};
      config.param=Object.assign(config.param,_param);

  }
  if(config.param){
    for(let key in config.param){
      s.push(`<input type='hidden' name='${key}' value='${config.param[key]}' />`)
    }

  }
  // let query=url.split("?")[1]
  // if(query){
  //   let tem=query.split("&");
  //   for(let i=0;i<tem.length;i++){
  //     if(tem[i])
  //     s.push( `<input type='hidden' name='${tem[i].split("=")[0]}' value='${tem[i].split("=")[1]}' />`)
  //   }
  // }
  form.innerHTML=s.join("");
  form.action=url;//.split("?")[0];
  form.method='POST';
  form.target="__downloadiframe__"
 // var link = document.createElement('a')
  let downlonifrem=document.getElementById("__downloadiframe__");
  if(!downlonifrem){
    let dev=document.createElement("div");
    document.body.appendChild(dev);
    dev.style.display='none';

    downlonifrem=document.createElement("iframe");
    downlonifrem.style.dispaly="none";
    downlonifrem.name='__downloadiframe__';
    downlonifrem.id='__downloadiframe__';
    downlonifrem.onload=function(){
    }
    dev.appendChild(downlonifrem);
  }
  //downlonifrem.src=url;
  form.submit();
  form.innerHTML="";
  form.action="";
  // link.href=url;
  // link.target='__downloadiframe__';
  // link.click();

}
export function login(config){
  let url=config.url;
  url=_getRealUrl(url,false,config)
  config.url=url;
  config.dataType='json'
  ajax(config)
}
